package com.usfot;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * Created by liyanxin on 2015/3/17.
 */
public class ZookeeperWathcherDemo {

    //互斥锁
    private static Integer mutex = new Integer(-1);

    public static void main(String args[]) throws KeeperException, InterruptedException, IOException {

        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 300000, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {
                System.out.println("状态:" + event.getState() + "|类型:" + event.getType() +
                        "|Wrapper:" + event.getWrapper() + "|Path:" + event.getPath());
            }
        });

        // 创建一个目录节点
        zk.create("/testRootPath", "testRootData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        // 创建一个子目录节点
        zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);


        zk.getData("/testRootPath/testChildPathOne", new Watcher() {
            @Override
            public void process(WatchedEvent event) {

                if (event.getState() == Event.KeeperState.SyncConnected
                        && event.getType() == Event.EventType.NodeDataChanged) {
                    System.out.println("znode:/testRootPath/testChildPathOne data change");
                    synchronized (mutex) {
                        mutex.notify();
                    }
                }
            }
        }, null);

        synchronized (mutex) {
            mutex.wait(); //阻塞直到notify
        }
        zk.close();
    }
}
